import { LoadingOutlined, PlusOutlined, CloseCircleOutlined } from '@ant-design/icons';
import { Upload, Image } from 'antd';
import { useEffect, useState } from 'react';

import commonService from '@/api/services/commonService';

export default function CommonUpload({
  isFile = false,
  isSingle = false,
  needParse = false,
  onChange,
  value,
}: any) {
  const [loading, setLoading] = useState(false);
  const [fileList, setFileList] = useState<any>([]);

  useEffect(() => {
    setImg();
  }, [value]);

  useEffect(() => {
    handleChange();
  }, [fileList]);

  const setImg = () => {
    if (value) {
      if (isSingle) {
        setFileList([value]);
      } else if (needParse) {
        setFileList(JSON.parse(value));
      } else {
        setFileList(value);
      }
    } else {
      setFileList([]);
    }
  };

  const remove = (index: number) => {
    if (isSingle || fileList.length === 1) {
      setFileList([]);
    } else {
      setFileList(fileList.splice(index, 1));
    }
  };

  const handleChange = () => {
    let upValue: any;
    if (isSingle) {
      upValue = fileList[0];
    } else if (needParse) {
      upValue = JSON.stringify(fileList);
    } else {
      upValue = fileList;
    }
    if (upValue !== value) {
      onChange(upValue);
    }
  };

  const handleUpload = ({ file }: any) => {
    setLoading(true);
    const formData = new FormData();
    formData.append('file', file);
    commonService.uploadApi(formData).then((res) => {
      setLoading(false);
      if (isSingle) {
        setFileList([res]);
      } else {
        setFileList([...fileList, res]);
      }
    });
  };

  const uploadButton = (
    <button style={{ border: 0, background: 'none' }} type="button">
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>上传</div>
    </button>
  );

  return (
    <div className={['flex', 'gap-[10px]', isFile ? 'flex-col' : ''].join(' ')}>
      <div className={['flex', 'gap-[10px]', isFile ? 'flex-col' : ''].join(' ')}>
        {fileList.map((item: string, index: number) => {
          return (
            <div key={index} className={['relative', isFile ? 'w-[332px]' : 'w-[102px]'].join(' ')}>
              {isFile ? <div>{item}</div> : <Image src={item} />}
              <CloseCircleOutlined
                onClick={() => remove(index)}
                className="absolute right-[-10px] top-[-10px] z-10 w-[20px]"
              />
            </div>
          );
        })}
      </div>
      <Upload
        listType="picture-card"
        maxCount={1}
        customRequest={handleUpload}
        showUploadList={false}
        action={`${import.meta.env.VITE_APP_BASE_API}/common/upload`}
      >
        {uploadButton}
      </Upload>
    </div>
  );
}
